package com.mnnu.controller;

import com.mnnu.pojo.Result;
import com.mnnu.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
public class UploadController {


    //将文件上传到本地
    /*@PostMapping("/upload")
    public Result upload(String username, Integer age, @RequestParam("image") MultipartFile file) throws IOException {
        log.info("文件上传：{}，{}，{}", username, age, file);
        //获取原始文件名称
        String originalFilename = file.getOriginalFilename();

        //构造唯一的文件名（不能重复） uuid（通用唯一之别码）d477b752-536a-4d3c-9cb6-8cd950b68e2a
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFilename = UUID.randomUUID().toString() + extname;
        log.info("新文件名" + newFilename);

        //将文件存储在服务器的磁盘目录中 E:\images
        file.transferTo(new File("E:\\images\\" + newFilename));

        return Result.success();
    }*/

    @Autowired
    private AliOSSUtils aliOSSUtils;
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("上传文件，文件名{}", image.getOriginalFilename());

        //将图片文件传入OSS存储,调用阿里云oss工具类
        String url = aliOSSUtils.upload(image);
        log.info("文件上传成功，文件访问url：{}", url);

        return Result.success(url);
    }
}
